package com.lovo;

import com.lovo.redis.dao.ITicketDao;
import com.lovo.redis.entity.TicketEntity;
import com.lovo.redis.vo.UserVo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@SpringBootTest(classes = com.lovo.RedisMain.class)
public class RedisT {
 @Autowired
 private RedisTemplate<String, Object> redisTemplate;

 @Autowired
 private ITicketDao ticketDao;
    @Test
    public void  stringT(){
//        String key="j192";
//     boolean bl=   redisTemplate.hasKey(key); //判断key是否存在
//        System.out.println(bl);
        /***********String*************/

        String key="user_key";
        UserVo vo=new UserVo();
        vo.setUserName("赵云");
        vo.setAge(20);
      redisTemplate.opsForValue().set(key,vo,10, TimeUnit.SECONDS);
       //取
       if(redisTemplate.hasKey(key)){
     LinkedHashMap map= (LinkedHashMap) redisTemplate.opsForValue().get(key);
           System.out.println(map.get("userName"));
       }else {
           System.out.println("redis中不存在");
       }
    }
    @Test
    public void  hashT(){
        //给key设置过期时间，通用
        redisTemplate.expire("key",3,TimeUnit.SECONDS);
      String key="hashKey";
        UserVo vo=new UserVo();
        vo.setUserName("赵云");
        vo.setAge(20);
        Map<String,Object> map=new HashMap<>();

        map.put("userName","赵云");
        map.put("age",20);
        map.put("vo",vo);
        redisTemplate.opsForHash().putAll(key,map);
        //修改年龄
       //1、判断删除的字段是否存在
        if(redisTemplate.opsForHash().hasKey(key,"age")){
          //  redisTemplate.opsForHash().delete(key,"age");
            redisTemplate.opsForHash().put(key,"age",30);
        }

      Object map1=  redisTemplate
              .opsForHash().get(key,"vo");
        Object map2=  redisTemplate
                .opsForHash().get(key,"userName");
        Object map3=  redisTemplate
                .opsForHash().get(key,"age");

        System.out.println(map1);

        //查询hash中的所有数据
    List<Object> list=    redisTemplate.opsForHash().values(key);
        System.out.println(list);
    }
   @Test
    public void listT() throws InterruptedException {
        String key="listKey";
        for(int i=0;i<10;i++) {
            redisTemplate.opsForList().rightPush(key, "a"+i);
            Thread.sleep(1000*3);
        }
    }

    @Test
    public void sava(){
        for (int i=0;i<10;i++){
            TicketEntity t=new TicketEntity();
            t.setMovieName("黑客帝国"+i);
            t.setNum(50+i);
            t.setPrice(88+i);
            t.setInfo("黑客帝国描述"+i);
            t.setMovieDate("2023-06-09");
            t =  ticketDao.save(t);

        }
    }
}
